package com.luoran.bartalks.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.core.UserContext;
import com.luoran.bartalks.core.ext.Pageable;
import com.luoran.bartalks.entity.BaseInfo;
import com.luoran.bartalks.entity.biz.BtUserMenu;
import com.luoran.bartalks.entity.biz.MenuInfo;
import com.luoran.bartalks.entity.biz.UserInfo;
import com.luoran.bartalks.service.IUserService;
import com.luoran.bartalks.utils.MD5;
import com.luoran.bartalks.utils.SysUtil;

@Controller
@RequestMapping("/userManage")
public class BtUserAction implements Pageable {

	@Autowired
	private IUserService userService;

	private static final Logger log = LoggerFactory.getLogger(BtUserAction.class);

	// 页面展示
	@RequestMapping
	public String show(Model model) {
		// 获取当前登录用户的用户类型
		model.addAttribute("userType", UserContext.get().getUserType());

		return "systemManage/user-list";
	}

	// 点击编辑获取用户信息
	@RequestMapping("/showItem/{id}")
	@ResponseBody
	public UserInfo getUserInfo(@PathVariable("id") String id) {
		log.info("获取用户信息>>>>>");
		return userService.getUserInfo(id);
	}

	// 编辑
	@RequestMapping("/editUserInfo")
	@ResponseBody
	public JSONObject editUserInfo(UserInfo info) {
		JSONObject result = new JSONObject();

		if (StringUtils.isEmpty(info.getNick().trim())) {
			result.put("msg", "昵称不能为空!");
			result.put("flag", false);
			return result;
		}

		info.setUpdateTime(new Date());// 设置更新时间
		int count = userService.editUserInfo(info);
		if (count == 1) {
			result.put("flag", true);
			result.put("msg", "操作成功!");
			return result;
		}
		result.put("flag", false);
		result.put("msg", "操作失败,请重试!");
		return result;
	}

	// 新增用户之前需要获取当前公司信息.
	@RequestMapping("/getCompanyInfo")
	@ResponseBody
	public JSONObject getCompanyInfo() {
		JSONObject result = new JSONObject();
		result.put("companyId", UserContext.get().getCompanyId());
		result.put("companyName", UserContext.get().getCompanyName());
		result.put("companyCode", UserContext.get().getCompanyCode());

		return result;

	}

	// 新增用户
	@RequestMapping("/addUser")
	@ResponseBody
	public JSONObject addUser(UserInfo info) {
		JSONObject obj = new JSONObject();

		String regex = "^[a-zA-Z][a-zA-Z0-9_]{4,15}$";
		if (!info.getLoginNo().matches(regex)) {
			obj.put("msg", "用户名需以5-16位字母开头,数字,下划线组成");
			obj.put("flag", false);
			return obj;
		}

		// 校验用户名唯一性
		log.info("用户名唯一性校验>>>");
		JSONObject result = checkUserName(info.getLoginNo());
		if (!result.getBooleanValue("flag")) {
			return result;
		}

		if (StringUtils.isEmpty(info.getNick().trim())) {
			obj.put("msg", "昵称不能为空!");
			obj.put("flag", false);
			return obj;
		}
		/*
		 * if (StringUtils.isEmpty(info.getRole())) { obj.put("flag", false);
		 * obj.put("msg", "角色不能为空!"); return obj; }
		 */

		info.setCreateTime(new Date());// 设置时间
		info.setLoginPwd(MD5.get("123456"));
		info.setStatus(0);
		info.setUserType(2);

		String uuid = userService.addUser(info);// 主键返回
		if (uuid != null) {
			/*
			 * //查询该用户角色的通用菜单 String role = info.getRole(); //查询该用户拥有角色,以及菜单
			 * List<BtRoleMenu> roleMenus = userService.getMenuByRole(role); //通过角色赋值菜单 for
			 * (int i = 0; i < roleMenus.size(); i++) { //获得菜单id //插入 BtUserMenu userMenu =
			 * new BtUserMenu(); userMenu.setUserId(uuid);
			 * userMenu.setMenuId(roleMenus.get(i).getMenuId()); userMenu.setStatus("0");
			 * userService.addMenuForUser(userMenu); }
			 */

			obj.put("flag", true);
			obj.put("msg", "操作成功!");
			return obj;
		} else {
			obj.put("flag", false);
			obj.put("msg", "操作失败,请重试!");
			return obj;
		}
	}

	// 用户名唯一性校验
	public JSONObject checkUserName(String loginNo) {
		JSONObject result = new JSONObject();
		// 查询用户名是否被占用
		UserInfo info = userService.checkUserName(loginNo);
		if (info != null) {
			log.info("<<<<<该用户名已被占用");
			result.put("flag", false);
			result.put("msg", "该用户名已被占用");
			return result;
		} else {
			result.put("flag", true);
			return result;
		}

	}

	// 删除用户
	@RequestMapping("/deleteItem/{id}")
	@ResponseBody
	public JSONObject deleteUserInfo(@PathVariable("id") String id) {
		JSONObject result = new JSONObject();
		UserInfo info = new UserInfo();
		info.setId(id);
		info.setStatus(1);
		info.setUpdateTime(new Date());
		int count = userService.updateStatus(info);
		if (count == 1) {
			result.put("flag", true);
			result.put("msg", "操作成功!");
			return result;
		}
		result.put("flag", false);
		result.put("msg", "操作失败,请重试!");
		return result;
	}

	/**
	 * 获取菜单树
	 * 
	 * @return
	 */
	@RequestMapping("/menuTree/{userId}")
	@ResponseBody
	public JSONObject getMenuTree(@PathVariable("userId") String userId) {
		log.info("获取菜单树>>>>>>>");
		JSONObject result = new JSONObject();
		List<JSONObject> treeData = new ArrayList<>();// 保存树信息
		List<MenuInfo> menuTree = userService.getMenuTree();
		List<BtUserMenu> userMenus = userService.getUserMenu(userId);

		if (menuTree == null) {
			result.put("flag", false);
			result.put("obj", "获取菜单树失败");
			log.info("获取菜单树失败<<<<<");
			return result;
		}
		// 遍历集合,把菜单封装到JSON格式的集合
		for (int i = 0; i < menuTree.size(); i++) {
			JSONObject obj = new JSONObject();
			obj.put("id", menuTree.get(i).getId());
			obj.put("menuName", menuTree.get(i).getMenuName());
			obj.put("menuIcon", menuTree.get(i).getMenuIcon());
			obj.put("menuNumber", menuTree.get(i).getMenuNumber());
			obj.put("menuUrl", menuTree.get(i).getMenuUrl());
			obj.put("parentId", menuTree.get(i).getParentId());
			obj.put("menuStatus", menuTree.get(i).getMenuStatus());
			treeData.add(obj);
		}

		// 遍历菜单树和用户菜单,获取已拥有菜单.添加checked属性
		for (int i = 0; i < treeData.size(); i++) {
			for (int j = 0; j < userMenus.size(); j++) {
				if ((treeData.get(i).getString("id")).equals(userMenus.get(j).getMenuId())) {
					treeData.get(i).put("checked", true);// 再给json添加一个key
				}
			}
		}

		result.put("flag", true);
		result.put("obj", treeData);
		return result;

	}

	/**
	 * 用户菜单分配
	 * 
	 * @param userId
	 * @param menuIds
	 * @return
	 */
	@RequestMapping("/menuManage")
	@ResponseBody
	public JSONObject menuManage(String userId, String menuIds) {
		JSONObject result = new JSONObject();

		// 把用户原有的菜单都删除.
		userService.deleteUserMenus(userId);

		String[] ids = menuIds.split(",");// 菜单ID集合
		for (String menuId : ids) {
			// 重新添加菜单
			BtUserMenu userMenu = new BtUserMenu();
			userMenu.setUserId(userId);
			userMenu.setMenuId(menuId);
			// 操作用户菜单
			String uuid = userService.addMenuForUser(userMenu);
			if (uuid == null) {
				result.put("msg", "操作失败");
				result.put("flag", false);
				return result;
			}
		}
		result.put("msg", "操作成功");
		result.put("flag", true);
		return result;
	}

	// 分页
	@Override
	public PageQuery<? extends BaseInfo> getQueryList(PageQuery<? extends BaseInfo> pageQuery) {
		if (StringUtils.isEmpty(pageQuery.getOrderBy())) {
			pageQuery.setOrderBy("create_time desc");
			@SuppressWarnings("unchecked")
			Map<String, Object> m = (Map<String, Object>) pageQuery.getParas();
			m.put("isSystemUser", SysUtil.isSystemUser());
			m.put("company_id", UserContext.get().getCompanyId());
		}
		return userService.getQueryList(pageQuery);
	}

}
